import { createRoot } from "react-dom/client";
import App from "@/app.tsx";
import "@/global.less";

// 解析 URL 中的 token（兼容 ?token=... 在 search 或 hash 中的场景）
function extractTokenFromUrl(): string | null {
  try {
    const tryParse = (query: string | null | undefined) => {
      if (!query) return null;
      const params = new URLSearchParams(query.startsWith('?') ? query : `?${query}`);
      const t = params.get('token');
      return t && t.trim() ? t.trim() : null;
    };
    const fromSearch = tryParse(window.location.search);
    if (fromSearch) return fromSearch;
    const hash = window.location.hash || '';
    const idx = hash.indexOf('?');
    if (idx >= 0) {
      const q = hash.substring(idx);
      const fromHash = tryParse(q);
      if (fromHash) return fromHash;
    }
  } catch {}
  return null;
}

// 从 JWT 中解析 payload（不做签名校验，仅用于读取 uid 等字段）
function decodeJwtPayload(token: string): any | null {
  try {
    const parts = token.split('.');
    if (parts.length < 2) return null;
    const base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
    const json = atob(padded);
    return JSON.parse(json);
  } catch {
    return null;
  }
}

// 去除 URL 中的 token 参数并保持当前路由
function removeTokenFromUrl() {
  try {
    const { protocol, host, pathname, search, hash } = window.location;
    const cleanSearch = (() => {
      const sp = new URLSearchParams(search);
      sp.delete('token');
      const s = sp.toString();
      return s ? `?${s}` : '';
    })();
    const cleanHash = (() => {
      if (!hash) return '';
      const h = hash.startsWith('#') ? hash.substring(1) : hash;
      const idx = h.indexOf('?');
      if (idx < 0) return `#${h}`;
      const base = h.substring(0, idx);
      const qs = h.substring(idx + 1);
      const sp = new URLSearchParams(qs);
      sp.delete('token');
      const s = sp.toString();
      return s ? `#${base}?${s}` : `#${base}`;
    })();
    const newUrl = `${protocol}//${host}${pathname}${cleanSearch}${cleanHash}`;
    window.history.replaceState(null, '', newUrl);
  } catch {}
}

// 登录成功后执行：写入本地并处理返回
(function handleGoogleLoginReturn() {
  try {
    const token = extractTokenFromUrl();
    if (!token) return;
    // 存储 token
    try { localStorage.setItem('token', token); } catch {}
    const payload = decodeJwtPayload(token) || {};
    const uid = payload?.uid ?? payload?.userId ?? payload?.id;
    // 合并写入 userData（保留原有信息）
    try {
      const raw = localStorage.getItem('userData');
      const prev = raw ? JSON.parse(raw) : {};
      const user_token = `Bearer ${token}`;
      const next = { ...prev, user_token, id: typeof uid !== 'undefined' ? uid : (prev?.id ?? undefined) };
      localStorage.setItem('userData', JSON.stringify(next));
    } catch {}
    // 通知应用内已登录
    try { window.dispatchEvent(new CustomEvent('auth:updated')); } catch {}
    // 清理地址栏中的 token
    removeTokenFromUrl();

    // 根据之前保存的返回状态进行跳转（如果存在）
    try {
      const raw = sessionStorage.getItem('login:return_state');
      if (raw) {
        const state = JSON.parse(raw);
        const targetUrl = state?.url;
        if (typeof targetUrl === 'string' && targetUrl) {
          // 使用 replace 避免产生历史记录回退再次触发
          window.location.replace(targetUrl);
        }
      }
    } catch {}
  } catch {}
})();

// 版本检查：每次发版把版本写入 localStorage，若版本不一致则清理除 "userData" 外的所有数据并刷新
try {
  const currentVersion = import.meta.env.VITE_APP_VERSION ?? "0.0.2";
  const storedVersion = localStorage.getItem("version");
  if (storedVersion !== currentVersion) {
    const userData = localStorage.getItem("userData");
    // 清空所有 localStorage
    localStorage.clear();
    // 恢复 userData（如果存在）并写入当前版本，避免刷新后再次触发清理
    if (userData) localStorage.setItem("userData", userData);
    localStorage.setItem("version", currentVersion);
    // 强制刷新以清除运行时缓存
    location.reload();
  } else {
    // 确保 version 存在
    localStorage.setItem("version", currentVersion);
  }
} catch (e) {
  // 在某些环境 localStorage 可能不可用，这里仅记录但不阻塞应用启动
  // eslint-disable-next-line no-console
  console.warn("Version check failed", e);
}

// 根据环境变量动态加载 vConsole（仅当 VITE_ENABLE_VCONSOLE === 'true' 时）
const enableVConsole = import.meta.env.VITE_ENABLE_VCONSOLE === 'true';
if (enableVConsole) {
  import('vconsole')
    .then(({ default: VConsole }) => {
      // eslint-disable-next-line no-new
      new VConsole();
      // eslint-disable-next-line no-console
      console.info('[VConsole] initialized');
    })
    .catch((e) => {
      // eslint-disable-next-line no-console
      console.warn('Failed to load vConsole', e);
    });
}

// 优化应用启动性能
const container = document.getElementById("root")!;
const root = createRoot(container);

// 使用React 18的并发特性优化首屏渲染
root.render(<App />);

if (import.meta.env.MODE === "production") {
  console.log("Version: ", import.meta.env.VITE_APP_VERSION);
  console.log(`Build time: ${__BUILD_INFO__.time}`);
  console.log(`Current branch: ${__BUILD_INFO__.branch}`);
}
